import React, { useState } from 'react';
import { Form, Input, Button, Checkbox, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import api from '../services/api';
import { useUser } from '../contexts/UserContext';

const LoginPage = () => {
  const [loading, setLoading] = useState(false);
  const history = useHistory();
  const { login } = useUser();

  const onFinish = async (values) => {
    setLoading(true);
    console.log('开始登录请求:', values);
    console.log('API Base URL:', process.env.REACT_APP_API_URL);
    console.log('完整请求URL:', `${process.env.REACT_APP_API_URL || 'http://localhost:8000/api'}/auth/login`);
    console.log('axios实例配置:', api.defaults);
    
    try {
      console.log('发送POST请求到 /auth/login');
      const response = await api.post('/auth/login', values);
      const { access_token } = response.data;
      
      console.log('登录成功:', { access_token });
      
      // 使用用户上下文的login方法
      await login(access_token);
      
      // 跳转到首页
      history.push('/');
      message.success('登录成功');
    } catch (error) {
      console.error('登录失败完整错误信息:', error);
      
      if (error.response) {
        // 服务器响应了错误
        console.log('服务器错误响应:', error.response);
        const errorMessage = error.response.data?.detail || '登录失败，请检查邮箱和密码';
        message.error(errorMessage);
      } else if (error.request) {
        // 请求发出但没有收到响应
        console.log('网络请求错误详情:', {
          request: error.request,
          config: error.config,
          code: error.code,
          message: error.message
        });
        console.log('请求URL:', error.config?.url);
        console.log('请求方法:', error.config?.method);
        console.log('请求头:', error.config?.headers);
        console.log('超时设置:', error.config?.timeout);
        message.error(`网络错误，请检查网络连接。请求URL: ${error.config?.url}`);
      } else {
        // 其他错误
        console.log('其他错误:', error.message);
        message.error('登录失败，请稍后重试');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ maxWidth: 300, margin: '100px auto' }}>
      <h2 style={{ textAlign: 'center', marginBottom: 30 }}>问题跟踪系统登录</h2>
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{ remember: true }}
        onFinish={onFinish}
      >
        <Form.Item
          name="email"
          rules={[{ required: true, message: '请输入邮箱!' }]}
        >
          <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="邮箱" />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: '请输入密码!' }]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="密码"
          />
        </Form.Item>
        <Form.Item>
          <Form.Item name="remember" valuePropName="checked" noStyle>
            <Checkbox>记住我</Checkbox>
          </Form.Item>
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button" loading={loading} block>
            登录
          </Button>
          或 <a href="/register">立即注册!</a>
        </Form.Item>
      </Form>
    </div>
  );
};

export default LoginPage;